import { DynamicModule, Global, Module } from '@nestjs/common';
import { ConfigureService } from './configure.service';
import { ConfigFactory, ConfigModule, ConfigModuleOptions } from '@nestjs/config';

import config from './config'

import * as fs from 'fs';
import * as path from 'path';
import * as yaml from 'js-yaml';



@Global()
export class ConfigureModule {
	static async forRoot(load:ConfigFactory = null): Promise<DynamicModule> {
		const loads:ConfigFactory[] = [config]
		if(load) {
			loads.push(load)
		}

		try {
			const folderPath = 'config'

			const files = await fs.promises.readdir(folderPath);
			for (const file of files) {
				const filePath = path.join(folderPath, file);
				

				loads.push(() => {
					return yaml.load(
						fs.readFileSync(filePath, 'utf8'),
					  ) as Record<string, any>
				})
			}
		} catch (err) {
			console.error(err);
		}

		
		const options:ConfigModuleOptions = {
			isGlobal : true,
			expandVariables : true,
			load : loads,
			envFilePath : [`.env.${process.env.APP_NAME}`, '.env', `.env.${process.env.NODE_ENV}`]
		}

		return {
			global: true,
			module: ConfigureModule,
			providers: [ConfigureService],
			exports: [ConfigureService],
			imports : [
				ConfigModule.forRoot(options)
			]
		}
	  }
}